/* components */
import { ConnectorModuleConnectorDialogDetail } from '@src/modules/connector/components'
/* hooks */
import { useDialog } from '@hooks/useDialog'
import { useConnectorCardSettingFetchConnectorOptions } from '@src/modules/connector/hooks'
/* model */
import { 
  ConnectorBizTypeEnum, 
  ConnectorDialogDetailData, 
  ConnectorModuleComponentNameEnum, 
  ConnectorOptionsAction, 
  ConnectorToField 
} from '@src/modules/connector/model'
import { flowMapState } from '@src/modules/setting/task/taskTypeSetting/flow/flowMap.js';
/* scss */
import '@src/modules/connector/components/card-item/index.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, defineComponent, PropType } from 'vue'
import { CommonComponentInstance } from '@model/VC'
import { CreateElement } from 'vue'
/* util */
import { createConnectorRuleFormItem, getShowFieldNameListByConnectorToFields } from '@src/modules/connector/util'
/* types */
import { ConnectorGetOptionsParams } from '@src/modules/connector/types'
import { t } from '@src/locales'

export type ConnectorModuleCreateConnectorDetailDialogProps = {
  title: string;
  visible: boolean;
  finishDisabled: boolean;
  value: ConnectorDialogDetailData;
  // 业务类型 id
  bizTypeId: string;
  toBizType: string;
  fromBizType: string;
  fromBizTypeName: string;
}

export interface ConnectorModuleCreateConnectorDetailDialogSetupState {
  
}

export enum ConnectorModuleCreateConnectorDetailDialogEmitEventNameEnum {
  Input = 'input',
  Close = 'close',
  Prev = 'prev',
  Next = 'next',
}

export type ConnectorModuleCreateConnectorDetailDialogInstance = ComponentInstance & ConnectorModuleCreateConnectorDetailDialogSetupState
export type ConnectorModuleCreateConnectorDetailDialogVM = ComponentRenderProxy<ConnectorModuleCreateConnectorDetailDialogProps> & CommonComponentInstance & ConnectorModuleCreateConnectorDetailDialogInstance

export default defineComponent({
  name: ConnectorModuleComponentNameEnum.ConnectorModuleCreateConnectorDetailDialog,
  emits: [
    ConnectorModuleCreateConnectorDetailDialogEmitEventNameEnum.Input,
    ConnectorModuleCreateConnectorDetailDialogEmitEventNameEnum.Close,
    ConnectorModuleCreateConnectorDetailDialogEmitEventNameEnum.Prev,
    ConnectorModuleCreateConnectorDetailDialogEmitEventNameEnum.Next,
  ],
  props: {
    bizTypeId: {
      type: String as PropType<string>,
      default: '',
    },
    toBizType: {
      type: String as PropType<string>,
      default: '',
    },
    fromBizType: {
      type: String as PropType<string>,
      default: '',
    },
    title: {
      type: String as PropType<string>,
      default: '',
    },
    finishDisabled: {
      type: Boolean as PropType<boolean>,
      default: false,
    },
    visible: {
      type: Boolean as PropType<boolean>,
      default: false,
    },
    isPaasAppChange: {
      type: Boolean as PropType<boolean>,
      default: false,
    },
    value: {
      type: Object as PropType<ConnectorDialogDetailData>,
      default: () => ({}),
    },
    fromBizTypeName: {
      type: String as PropType<string>,
      default: ''
    },
    bizActionCode: {
      type: String as PropType<string>,
      default: '',
    },
    currentNodeId: {
      type: String as PropType<string>,
      default: '',
    }
  },
  setup(props: ConnectorModuleCreateConnectorDetailDialogProps, { emit }) {
    
    // 连接器配置
    const {
      loading: fetchConnectorOptionsLoading, 
      connectorOptions, 
      fetchConnectorOptions 
    } = useConnectorCardSettingFetchConnectorOptions()
    
    const { visible: insideVisible, showDialog, hideDialog } = useDialog()
    
    // form-builder 组件引用名称
    const formBuildComponentRef = 'FormBuilderComponent'
    
    // 关闭事件
    const onDialogCloseHandler = () => {
      emit(ConnectorModuleCreateConnectorDetailDialogEmitEventNameEnum.Close)
    }
    
    // 上一步事件
    const onDialogPrevHandler = () => {
      emit(ConnectorModuleCreateConnectorDetailDialogEmitEventNameEnum.Prev)
    }
    
    return {
      insideVisible,
      formBuildComponentRef,
      
      fetchConnectorOptionsLoading,
      connectorOptions,
      
      showDialog,
      hideDialog,
      
      onDialogCloseHandler,
      onDialogPrevHandler,
      
      fetchConnectorOptions,
    }
  },
  computed: {
    disabled(): boolean {
      return this.fetchConnectorOptionsLoading || this.finishDisabled
    },
    detailValue(): ConnectorDialogDetailData {
      const value = {
        ...this.value,
        actionList: this.connectorOptions.actionList,
        fromFieldList: this.connectorOptions.fromFieldList,
        // toFieldList: this.connectorOptions.toFieldList || []
      }

      // @ts-ignore
      const state = this.bizActionCode === 'normal' ? this.currentNodeId : flowMapState[this.bizActionCode];
      if(state) {
        value.stateCanEdit = [state];
      }

      return value;
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(newValue) {
        
        if (newValue) {
          this.onVisibleShowHandler()
        } else {
          this.onVisibleHideHandler()
        }
        
      }
    }
  },
  methods: {
    /**
     * @description 取消
    */
    cancel() {
      this.hideDialog()
      this.onDialogPrevHandler()
    },
    /**
     * @description 完成
    */
    async finish() {  
      this.onDialogNextHandler()
    },
    /** 
     * @description 获取 连接器配置
    */
    fetchConnectorOptionsImpl() {
    
      // toBizType 根据选择关联应用对应的type获取
      const params: ConnectorGetOptionsParams = {
        fromBizTypeId: this.value.bizTypeId,
        toBizTypeId: this.value.paasApp.id,
        fromBizType: this.fromBizType as ConnectorBizTypeEnum,
        toBizType: this.value.paasApp.type as ConnectorBizTypeEnum,
      }
      
      this.fetchConnectorOptions(params).then(() => {
        
        const initSelectedActionList = this.getInitSelectedActionList()
        // const actionsValue = initSelectedActionList.map((item) => item?.action || '')
        
        // const toFieldList: ConnectorToField[] = this.connectorOptions.toFieldList.filter(item => item.supportInsert)
        
        const selectRuleForms = [
          // 默认插入一条空数据
          createConnectorRuleFormItem()
        ]
        
        // 注释了这里的一加载时候去插入数据因为相关插入需要选择插入动作，相关更新insertRuleForms在选择对应的动作方法里
        /* const insertRuleForms = toFieldList.map(toField => {
          return createConnectorRuleFormItem(toField)
        })
        */
        const newValue: ConnectorDialogDetailData = {
          ...this.value,
          actionsValue: initSelectedActionList,
          selectRuleForms,
          insertRuleForms: [],
          showFieldNameList: []
        }

        this.onValueInputHandler(newValue)
  
        
      })
      
    },
    /** 
     * @description 获取初始化当前选中的 执行动作列表
    */
    getInitSelectedActionList(): ConnectorOptionsAction[] {
      return this.connectorOptions.actionList.filter(action => action.selected)
    },
    /**
    * @description 获取属性列表
    * @return {Record<string, any>} 属性列表
    */  
    getAttributes(): Record<string, any> {
      return {
        class: ConnectorModuleComponentNameEnum.ConnectorModuleCreateConnectorDetailDialog,
        props: {
          title: this.title,
          show: this.insideVisible,
          appendToBody: true
        },
        on: {
          'update:show': () => {
            this.hideDialog()
          },
          'closed': () => {
            this.onDialogPrevHandler()
          }
        }
      }
    },
    /** 
     * @description 获取 loading 加载指令属性
    */
    getLoadingAttributes(): Record<string, any> {
      return {
        directives: [
          {
            name: 'loading',
            value: this.fetchConnectorOptionsLoading
          }
        ]
      }
    },
    /** 
     * @description 下一步事件
    */
    onDialogNextHandler() {
      this.$emit(ConnectorModuleCreateConnectorDetailDialogEmitEventNameEnum.Next, this.detailValue)
    },
    /** 
     * @description 弹窗显示事件
    */
    onVisibleShowHandler() {
      // 切换了选择paas表单再重新获取detailValue
      this.fetchConnectorOptionsImpl() 
      this.showDialog()
    },
    /** 
     * @description 弹窗隐藏事件
    */
    onVisibleHideHandler() {
      this.hideDialog()
    },
    /** 
     * @description 值数据变化事件
    */
    onValueInputHandler(value: ConnectorDialogDetailData) {
      this.$emit(ConnectorModuleCreateConnectorDetailDialogEmitEventNameEnum.Input, value)
    },
    /** 
     * @description 上一步
    */
    prev() {
      this.onDialogPrevHandler()
    },
  },
  render(h: CreateElement) {
    
    const attrs = this.getAttributes()
    const attrs_loading = this.getLoadingAttributes()
    
    return (
      <base-modal {...attrs}>
        
        {this.insideVisible && (
          <ConnectorModuleConnectorDialogDetail 
            {...attrs_loading}
            value={this.detailValue}
            fromBizTypeName={this.fromBizTypeName}
            onInput={this.onValueInputHandler}
          />
        )}
        
        <div class="dialog-footer" slot="footer">
          
          <el-button
            disabled={this.disabled}
            onClick={this.cancel}
          >
            {t('common.base.cancel')}
          </el-button>
          
          <el-button 
            disabled={this.disabled}
            onClick={this.prev}
          >
            {t('common.base.steps.previous')}
          </el-button>
          
          <el-button 
            type="primary" 
            disabled={this.disabled}
            onClick={this.finish}
          >
            {t('common.base.finish')}
          </el-button>
          
        </div>
        
      </base-modal>
    )
  }
})
